﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX.D3DCompiler;
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
using Apparat.ShaderManagement;

namespace Apparat.Renderables
{
  public class TriangleEF : Renderable
  {
    SlimDX.Direct3D11.Buffer vertexBuffer;

    public TriangleEF()
    {
      // create test vertex data, making sure to rewind the stream afterward
      var vertices = new DataStream(12 * 3, true, true);
      vertices.Write(new Vector3(0.0f, 0.5f, 0.5f));
      vertices.Write(new Vector3(0.5f, -0.5f, 0.5f));
      vertices.Write(new Vector3(-0.5f, -0.5f, 0.5f));
      vertices.Position = 0;

      // create the vertex buffer
      vertexBuffer = new SlimDX.Direct3D11.Buffer(
          DeviceManager.Instance.device,
          vertices,
          12 * 3,
          ResourceUsage.Default,
          BindFlags.VertexBuffer,
          CpuAccessFlags.None,
          ResourceOptionFlags.None,
          0);
    }

    public override void Dispose()
    {
      vertexBuffer.Dispose();
    }

    EffectWrapperTransformEffect ew = ShaderManager.Instance.transformEffect;

    public override void Render()
    {
      Matrix ViewPerspective = CameraManager.Instance.ViewPerspective;
      Matrix WorldViewPerspective = this.transform * ViewPerspective;
      ew.tmat.SetMatrix(WorldViewPerspective);

      // configure the Input Assembler portion of the pipeline with the vertex data
      DeviceManager.Instance.context.InputAssembler.InputLayout = ew.layout;
      DeviceManager.Instance.context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
      DeviceManager.Instance.context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 12, 0));

      ew.technique = ew.effect.GetTechniqueByName("Render");

      EffectTechniqueDescription techDesc;
      techDesc = ew.technique.Description;

      for (int p = 0; p < techDesc.PassCount; ++p)
      {
        ew.technique.GetPassByIndex(p).Apply(DeviceManager.Instance.context);
        DeviceManager.Instance.context.Draw(3, 0);
      }
    }

    public override Matrix Transform
    {
      get
      {
        return this.transform;
      }
      set
      {
        this.transform = value;
      }
    }
  }
}
